<template>
	<view class="container">
		<uni-forms ref="customForm" :rules="customRules" :modelValue="customFormData" label-width="140rpx">
			<uni-forms-item label="联系人:" required name="username">
				<uni-easyinput v-model="customFormData.username" placeholder="请输入联系人姓名" />
			</uni-forms-item>
			<uni-forms-item label="手机号:" required name="phone">
				<uni-easyinput v-model="customFormData.phone" placeholder="请输入手机号" />
			</uni-forms-item>
			<uni-forms-item label="所在地区:" required name="area">
				<uni-data-picker :localdata="localData" popup-title="请选择省市区" @change="onchange"
					@nodeclick="onnodeclick">
				</uni-data-picker>
			</uni-forms-item>
			<uni-forms-item label="详细地址:" name="address">
				<uni-easyinput type="textarea" v-model="customFormData.address" placeholder="请输入详细地址" />
			</uni-forms-item>
			<view class="btn">
				<button @click="customFormData.role='好大哥'" :class="customFormData.role=='好大哥'?'active':''">好大哥</button>
				<button @click="customFormData.role='好大姐'" :class="customFormData.role=='好大姐'?'active':''"
					class="right">好大姐</button>
			</view>
		</uni-forms>
		<view class="submit" @click="saveAddress">
			保存
		</view>
	</view>
</template>

<script>
	import cityData from './city.json'
	import {
		request
	} from '@/utils/request.js';
	export default {
		data() {
			return {
				localData: [],
				customFormData: {
					username: '',
					phone: '',
					area: '',
					address: '',
					role: ''
				},
				customRules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					age: {
						rules: [{
							required: true,
							errorMessage: '年龄不能为空'
						}]
					},
					hobby: {
						rules: [{
								format: 'array'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									if (value.length < 2) {
										callback('请至少勾选两个兴趣爱好')
									}
									return true
								}
							}
						]
					}

				},
			};
		},
		onLoad() {
			console.log(cityData, 'cityData');
			// 省市区数据树生成
			this.localData = this.get_city_tree()
			// console.log(JSON.stringify(this.localData))
		},
		methods: {
			async saveAddress() {
				const data = await request({
					url: '/api/address/save',
					method: 'POST',
					data: {
						name: this.customFormData.username,
						phone: this.customFormData.phone,
						province_code: this.customFormData.area,
						city_code: this.customFormData.area,
						district_code: this.customFormData.area,
						address: this.customFormData.address,
						category: '家',
						is_default: this.customFormData.role
					},
					header: {
						Authorization: 'Bearer ' + uni.getStorageSync('token')
					}
				})
				uni.showToast({
					title: data.message,
					icon: 'none'
				})
			},
			// 节点变化后 （并非已经选择完毕）
			onnodeclick(node) {
				this.customFormData.area = node.value
				console.log(node, '~~~');
				// console.log(JSON.stringify(node))
			},
			// 整体选择完成以后
			onchange(e) {
				const value = e.detail.value
				console.log(JSON.stringify(value))
			},
			// 省市区数据树生成
			get_city_tree() {
				let res = []
				if (cityData.length) {
					// 递归生成
					res = this.handleTree(cityData)
				}
				return res
			},
			handleTree(data, parent_code = null) {
				let res = []

				let keys = {
					id: 'code',
					pid: 'parent_code',
					children: 'children',

					text: 'name',
					value: 'code'
				}

				let oneItemDEMO = {
					text: '',
					value: '',
					children: []
				}
				let oneItem = {}

				// 循环
				for (let index in data) {
					// 判断
					if (parent_code === null) {
						// 顶级菜单 - 省
						if (!data[index].hasOwnProperty(keys.pid) || data[index][keys.pid] == parent_code) {
							// 不存在parent_code，或者已匹配
							oneItem = JSON.parse(JSON.stringify(oneItemDEMO))
							oneItem.text = data[index][keys.text]
							oneItem.value = data[index][keys.value]

							// 递归下去
							oneItem.children = this.handleTree(data, data[index][keys.id])
							res.push(oneItem)

						} else {
							// 匹配不到，跳过
						}

					} else {
						// 非顶级菜单 - 市、区、街道
						if (data[index].hasOwnProperty(keys.pid) && data[index][keys.pid] == parent_code) {
							// 已匹配
							oneItem = JSON.parse(JSON.stringify(oneItemDEMO))
							oneItem.text = data[index][keys.text]
							oneItem.value = data[index][keys.value]

							// 递归下去
							oneItem.children = this.handleTree(data, data[index][keys.id])
							res.push(oneItem)

						} else {
							// 匹配不到，跳过
						}

					}

				}

				return res
			}
		}
	}
</script>

<style lang="scss">
	.container {
		width: 610rpx;
		height: 659rpx;
		background: #FFFFFF;
		border-radius: 24rpx;
		margin: 24rpx auto;
		padding: 50rpx 35rpx;
		padding-bottom: 0;
	}

	.btn {
		display: flex;

		button {
			background: #FFFFFF;
			border-radius: 18rpx;
			border: 1px solid #333333;
			text-align: center;
			margin: 0;
			// padding: 14rpx 20rpx;
		}

		.active {
			background: #5A2F83;
			color: white;
		}

		.right {
			margin-left: 24rpx;
		}
	}

	.submit {
		width: 613rpx;
		height: 95rpx;
		background: #5A2F83;
		border-radius: 10rpx;
		margin: auto;
		margin-top: 116rpx;
		text-align: center;
		line-height: 95rpx;
		color: white;
	}
</style>